package com.bysj.agent.config;

import cn.dev33.satoken.config.SaTokenConfig;
import feign.RequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;



public class FeignConfig {

    @Autowired
    private SaTokenConfig saTokenConfig;

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request =  attributes.getRequest();
                
                // 获取Sa-Token配置中的实际token名称
                String tokenName = saTokenConfig.getTokenName();
                String tokenValue = request.getHeader(tokenName);
                
                if (tokenValue != null) {
                    requestTemplate.header(tokenName, tokenValue);
                }
                
                // 也复制Authorization头(如果存在)，以支持其他认证方式
                String authHeader = request.getHeader("Authorization");
                if (authHeader != null) {
                    requestTemplate.header("Authorization", authHeader);
                }
            }
        };
    }
}